package com.gszy.auth.database;


import com.gszy.auth.utils.StringUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

/**
 * @author MeUChT
 */
public class BeanHandler<T> implements ResultSetHandler<T>{

    private Class<T> beanClass;

    public BeanHandler(Class<T> beanClass){
        this.beanClass = beanClass;
    }


    @Override
    public T handler(ResultSet resultSet) {
        T bean = null;
        try {
            while (resultSet.next()){
                bean = beanClass.newInstance();
                ResultSetMetaData metaData = resultSet.getMetaData();
                int columnCount = metaData.getColumnCount();
                for (int i = 1;i<= columnCount;i++){

                    //phone_num -> phoneNum
                    String columnName = metaData.getColumnName(i);
                    Object columnValue = resultSet.getObject(columnCount);
                    String camelCase = StringUtils.toCamelCase(columnName);
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(
                            camelCase,beanClass
                    );
                    //setXXX() isXXX() void
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    writeMethod.invoke(bean,columnValue);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return bean;
    }
}
